package com.cdk8s.example.simplespringboot.utils;


import lombok.extern.slf4j.Slf4j;
import org.apache.batik.transcoder.TranscoderException;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.ImageTranscoder;
import org.apache.batik.transcoder.image.PNGTranscoder;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * svg 图片操作类.
 */
@Slf4j
public final class SvgUtil {

	/**
	 * 把本地 svg 保存到本地磁盘
	 */
	public static Boolean localSvgToPngFile(String fullLocalPath, String pngFileFullPath, Integer width, Integer height) {
		if (StringUtil.isBlank(fullLocalPath)) {
			throw new RuntimeException("文件路径不能为空");
		}

		OutputStream outputStream = null;
		try {
			TranscoderInput transcoderInput = new TranscoderInput(FileUtil.getLocalFileToInputStream(fullLocalPath));
			outputStream = new FileOutputStream(pngFileFullPath);
			TranscoderOutput transcoderOutput = new TranscoderOutput(outputStream);

			// Convert SVG to PNG and Save to File System
			PNGTranscoder pngTranscoder = new PNGTranscoder();

			if (null != width && null != height) {
				pngTranscoder.addTranscodingHint(ImageTranscoder.KEY_WIDTH, new Float(width));
				pngTranscoder.addTranscodingHint(ImageTranscoder.KEY_HEIGHT, new Float(height));
			}

			pngTranscoder.transcode(transcoderInput, transcoderOutput);
		} catch (Exception e) {
			log.error("------zch------fullLocalPath 保存失败 <{}>", fullLocalPath);
			ExceptionUtil.printStackTraceAsString(e);
			return false;
		} finally {
			if (null != outputStream) {
				try {
					outputStream.flush();
					outputStream.close();
				} catch (Exception e) {
					ExceptionUtil.printStackTraceAsString(e);
				}
			}
		}
		return true;
	}

	/**
	 * 把网络 svg 保存到本地磁盘
	 */
	public static Boolean networkSvgToPngFile(String svgUrl, String pngFileFullPath, Integer width, Integer height) {
		if (StringUtil.isBlank(svgUrl)) {
			throw new RuntimeException("文件地址不能为空");
		}

		OutputStream outputStream = null;
		try {
			TranscoderInput transcoderInput = new TranscoderInput(svgUrl);
			outputStream = new FileOutputStream(pngFileFullPath);
			TranscoderOutput transcoderOutput = new TranscoderOutput(outputStream);

			// Convert SVG to PNG and Save to File System
			PNGTranscoder pngTranscoder = new PNGTranscoder();

			if (null != width && null != height) {
				pngTranscoder.addTranscodingHint(ImageTranscoder.KEY_WIDTH, new Float(width));
				pngTranscoder.addTranscodingHint(ImageTranscoder.KEY_HEIGHT, new Float(height));
			}

			pngTranscoder.transcode(transcoderInput, transcoderOutput);
		} catch (Exception e) {
			log.error("------zch------svgUrl 保存失败 <{}>", svgUrl);
			ExceptionUtil.printStackTraceAsString(e);
			return false;
		} finally {
			if (null != outputStream) {
				try {
					outputStream.flush();
					outputStream.close();
				} catch (Exception e) {
					ExceptionUtil.printStackTraceAsString(e);
				}
			}
		}
		return true;
	}

	/**
	 * 把网络 svg 保存到本地磁盘（保持原大小）
	 */
	public static void networkSvgToPngFile(String svgUrl, String pngFileFullPath) {
		networkSvgToPngFile(svgUrl, pngFileFullPath, null, null);
	}


	/**
	 * 将svg字符串转换为png
	 *
	 * @param svgCode     svg代码
	 * @param pngFilePath 保存的路径
	 * @throws TranscoderException svg代码异常
	 * @throws IOException         io错误
	 */
	public static Boolean svgCodeToPngFile(String svgCode, String pngFilePath) throws IOException, TranscoderException {
		File file = new File(pngFilePath);
		FileOutputStream outputStream = null;
		try {
			file.createNewFile();
			outputStream = new FileOutputStream(file);
			svgCodeToPngFile(svgCode, outputStream);
		} catch (Exception e) {
			ExceptionUtil.printStackTraceAsString(e);
			return false;
		} finally {
			if (outputStream != null) {
				try {
					outputStream.flush();
					outputStream.close();
				} catch (Exception e) {
					ExceptionUtil.printStackTraceAsString(e);
				}
			}
		}
		return true;
	}

	/**
	 * 将svgCode转换成png文件，直接输出到流中
	 *
	 * @param svgCode      svg代码
	 * @param outputStream 输出流
	 * @throws TranscoderException 异常
	 * @throws IOException         io异常
	 */
	public static Boolean svgCodeToPngFile(String svgCode, OutputStream outputStream) throws TranscoderException, IOException {
		try {
			byte[] bytes = svgCode.getBytes(StandardCharsets.UTF_8);
			PNGTranscoder pngTranscoder = new PNGTranscoder();
			TranscoderInput input = new TranscoderInput(new ByteArrayInputStream(bytes));
			TranscoderOutput output = new TranscoderOutput(outputStream);
			// 增加图片的属性设置(单位是像素)---下面是写死了，实际应该是根据SVG的大小动态设置，默认宽高都是400
			// pngTranscoder.addTranscodingHint(ImageTranscoder.KEY_WIDTH, new Float(400));
			// pngTranscoder.addTranscodingHint(ImageTranscoder.KEY_HEIGHT, new Float(300));
			pngTranscoder.transcode(input, output);
		} catch (Exception e) {
			ExceptionUtil.printStackTraceAsString(e);
			return false;
		} finally {
			if (outputStream != null) {
				try {
					outputStream.flush();
					outputStream.close();
				} catch (Exception e) {
					ExceptionUtil.printStackTraceAsString(e);
				}
			}
		}
		return true;
	}

}

